package com.feeyin.radar.crm.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.view.RedirectView;

import com.feeyin.radar.commons.BigDecimalPropertyEditor;
import com.feeyin.radar.commons.DatePropertyEditor;
import com.feeyin.radar.commons.FileUtils;
import com.feeyin.radar.commons.Page;
import com.feeyin.radar.commons.StringUtils;
import com.feeyin.radar.crm.form.ContractCaseForm;
import com.feeyin.radar.crm.form.ContractForm;
import com.feeyin.radar.crm.form.CostForm;
import com.feeyin.radar.crm.form.InvoiceForm;
import com.feeyin.radar.crm.form.InvoiceNewForm;
import com.feeyin.radar.crm.form.UploadFileForm;
import com.feeyin.radar.crm.model.CodeStore;
import com.feeyin.radar.crm.model.Contract;
import com.feeyin.radar.crm.model.ContractCase;
import com.feeyin.radar.crm.model.ContractCaseType;
import com.feeyin.radar.crm.model.ContractDetail;
import com.feeyin.radar.crm.model.CostManage;
import com.feeyin.radar.crm.model.Invoice;
import com.feeyin.radar.crm.model.QueryContract;
import com.feeyin.radar.crm.model.SystemFile;
import com.feeyin.radar.crm.service.ContractBackCostService;
import com.feeyin.radar.crm.service.ContractCaseService;
import com.feeyin.radar.crm.service.ContractInvoiceService;
import com.feeyin.radar.crm.service.ContractService;
import com.feeyin.radar.crm.service.CustomerService;
import com.feeyin.radar.crm.service.SystemFileService;
import com.feeyin.radar.sys.model.Users;
import com.feeyin.radar.sys.service.DepartmentService;
import com.feeyin.radar.sys.service.UserService;

public class ContractManageController extends MultiActionController {
	private CustomerService customerService;
	private ContractService contractService;
	private ContractCaseService contractCaseService;
	private UserService userService;
	private SystemFileService systemFileService;
	private ContractBackCostService contractBackCostService;
	private ContractInvoiceService contractInvoiceService;
	private DepartmentService departmentService;
	private String contractManage;
	private String selectCustomer;
	private String selectSalePerson;
	private String addContract;
	private String addContractN;
	private String updateContract;
	private String stopContract;
	private String waitAuditContract;
	private String returnContract;
	private String closedContract;
	private String deptContract;
	private String importContract;
	private String contractDetail;
	private String contractUpdateHistory;
	private String cancelContract;
	private String viewBackCostInvoice;
	private String addInvoice;
	private String advancedQueryContract;
	private String updateContractProName;
	private String selectContractCaseType;
	private String preAddContractCase;
	private String selectCaseType;// Display CaseType Choose
	private String selectProcess;// Display Process Group
	private String viewContractCase;// Display Contract Case Detail View
	private String updateContractCase; // Update Contract Case
	private String selectProcessDetail; // Display Process
	private String addContractCase;
	private String ajaxCaseType;
	private String allCase;
	private String caseDetail;
	private String selectContractList;
	private String addReverseInvoice;
	private String reverseInvoiceDetail;
	
	private String addOfficialCost;
	private String addOperationCost;
	
	private String deptCost;
	private String costDetail;
	
	public String getAllCase ()
	{
		return allCase;
	}

	public void setAllCase (String allCase)
	{
		this.allCase = allCase;
	}

	public String getCaseDetail ()
	{
		return caseDetail;
	}

	public void setCaseDetail (String caseDetail)
	{
		this.caseDetail = caseDetail;
	}

	public String getCostDetail() {
		return costDetail;
	}

	public void setCostDetail(String costDetail) {
		this.costDetail = costDetail;
	}

	public String getDeptCost() {
		return deptCost;
	}

	public void setDeptCost(String deptCost) {
		this.deptCost = deptCost;
	}

	public String getAddOfficialCost() {
		return addOfficialCost;
	}

	public void setAddOfficialCost(String addOfficialCost) {
		this.addOfficialCost = addOfficialCost;
	}

	public String getAddOperationCost() {
		return addOperationCost;
	}

	public void setAddOperationCost(String addOperationCost) {
		this.addOperationCost = addOperationCost;
	}

	public String getReverseInvoiceDetail() {
		return reverseInvoiceDetail;
	}

	public void setReverseInvoiceDetail(String reverseInvoiceDetail) {
		this.reverseInvoiceDetail = reverseInvoiceDetail;
	}

	public String getAddReverseInvoice() {
		return addReverseInvoice;
	}

	public void setAddReverseInvoice(String addReverseInvoice) {
		this.addReverseInvoice = addReverseInvoice;
	}

	public String getSelectContractList() {
		return selectContractList;
	}

	public void setSelectContractList(String selectContractList) {
		this.selectContractList = selectContractList;
	}

	public ContractCaseService getContractCaseService() {
		return contractCaseService;
	}

	public String getAjaxCaseType() {
		return ajaxCaseType;
	}

	public void setAjaxCaseType(String ajaxCaseType) {
		this.ajaxCaseType = ajaxCaseType;
	}

	public String getPreAddContractCase() {
		return preAddContractCase;
	}

	public void setPreAddContractCase(String preAddContractCase) {
		this.preAddContractCase = preAddContractCase;
	}

	public String getAddContractCase() {
		return addContractCase;
	}

	public void setAddContractCase(String addContractCase) {
		this.addContractCase = addContractCase;
	}

	public String getSelectCaseType() {
		return selectCaseType;
	}

	public void setSelectCaseType(String selectCaseType) {
		this.selectCaseType = selectCaseType;
	}

	public String getSelectProcess() {
		return selectProcess;
	}

	public void setSelectProcess(String selectProcess) {
		this.selectProcess = selectProcess;
	}

	public String getViewContractCase() {
		return viewContractCase;
	}

	public void setViewContractCase(String viewContractCase) {
		this.viewContractCase = viewContractCase;
	}

	public String getUpdateContractCase() {
		return updateContractCase;
	}

	public void setUpdateContractCase(String updateContractCase) {
		this.updateContractCase = updateContractCase;
	}

	public String getSelectProcessDetail() {
		return selectProcessDetail;
	}

	public void setSelectProcessDetail(String selectProcessDetail) {
		this.selectProcessDetail = selectProcessDetail;
	}

	public DepartmentService getDepartmentService() {
		return this.departmentService;
	}

	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}

	public String getAddContractN() {
		return this.addContractN;
	}

	public void setAddContractN(String addContractN) {
		this.addContractN = addContractN;
	}

	public String getUpdateContractProName() {
		return this.updateContractProName;
	}

	public void setUpdateContractProName(String updateContractProName) {
		this.updateContractProName = updateContractProName;
	}

	public CustomerService getCustomerService() {
		return this.customerService;
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	public ContractService getContractService() {
		return this.contractService;
	}

	public void setContractService(ContractService contractService) {
		this.contractService = contractService;
	}

	public UserService getUserService() {
		return this.userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public SystemFileService getSystemFileService() {
		return this.systemFileService;
	}

	public void setSystemFileService(SystemFileService systemFileService) {
		this.systemFileService = systemFileService;
	}

	public ContractBackCostService getContractBackCostService() {
		return this.contractBackCostService;
	}

	public void setContractBackCostService(
			ContractBackCostService contractBackCostService) {
		this.contractBackCostService = contractBackCostService;
	}

	public ContractInvoiceService getContractInvoiceService() {
		return this.contractInvoiceService;
	}

	public void setContractInvoiceService(
			ContractInvoiceService contractInvoiceService) {
		this.contractInvoiceService = contractInvoiceService;
	}

	public String getContractManage() {
		return this.contractManage;
	}

	public void setContractManage(String contractManage) {
		this.contractManage = contractManage;
	}

	public String getAddContract() {
		return this.addContract;
	}

	public void setAddContract(String addContract) {
		this.addContract = addContract;
	}

	public String getSelectCustomer() {
		return this.selectCustomer;
	}

	public void setSelectCustomer(String selectCustomer) {
		this.selectCustomer = selectCustomer;
	}

	public String getUpdateContract() {
		return this.updateContract;
	}

	public void setUpdateContract(String updateContract) {
		this.updateContract = updateContract;
	}

	public String getSelectSalePerson() {
		return this.selectSalePerson;
	}

	public void setSelectSalePerson(String selectSalePerson) {
		this.selectSalePerson = selectSalePerson;
	}

	public String getWaitAuditContract() {
		return this.waitAuditContract;
	}

	public void setWaitAuditContract(String waitAuditContract) {
		this.waitAuditContract = waitAuditContract;
	}

	public String getReturnContract() {
		return this.returnContract;
	}

	public void setReturnContract(String returnContract) {
		this.returnContract = returnContract;
	}

	public String getStopContract() {
		return this.stopContract;
	}

	public void setStopContract(String stopContract) {
		this.stopContract = stopContract;
	}

	public String getClosedContract() {
		return this.closedContract;
	}

	public void setClosedContract(String closedContract) {
		this.closedContract = closedContract;
	}

	public String getDeptContract() {
		return this.deptContract;
	}

	public void setDeptContract(String deptContract) {
		this.deptContract = deptContract;
	}

	public String getImportContract() {
		return this.importContract;
	}

	public void setImportContract(String importContract) {
		this.importContract = importContract;
	}

	public String getContractDetail() {
		return this.contractDetail;
	}

	public void setContractDetail(String contractDetail) {
		this.contractDetail = contractDetail;
	}

	public String getContractUpdateHistory() {
		return this.contractUpdateHistory;
	}

	public void setContractUpdateHistory(String contractUpdateHistory) {
		this.contractUpdateHistory = contractUpdateHistory;
	}

	public String getCancelContract() {
		return this.cancelContract;
	}

	public void setCancelContract(String cancelContract) {
		this.cancelContract = cancelContract;
	}

	public String getViewBackCostInvoice() {
		return this.viewBackCostInvoice;
	}

	public void setViewBackCostInvoice(String viewBackCostInvoice) {
		this.viewBackCostInvoice = viewBackCostInvoice;
	}

	public String getAddInvoice() {
		return this.addInvoice;
	}

	public void setAddInvoice(String addInvoice) {
		this.addInvoice = addInvoice;
	}

	public String getAdvancedQueryContract() {
		return this.advancedQueryContract;
	}

	public void setAdvancedQueryContract(String advancedQueryContract) {
		this.advancedQueryContract = advancedQueryContract;
	}

	public String getSelectContractCaseType() {
		return selectContractCaseType;
	}

	public void setSelectContractCaseType(String selectContractCaseType) {
		this.selectContractCaseType = selectContractCaseType;
	}

	public ModelAndView display(HttpServletRequest request,
			HttpServletResponse response, QueryContract queryContract) {
		Map map = new HashMap();
		Integer userId = (Integer) request.getSession().getAttribute("userId");

		String isViewAllContract = (String) request.getSession().getAttribute(
				"isViewAllContract");

		String sFlag = request.getParameter("sFlag");
		map.put("sFlag", sFlag);
		String customerName = "";
		if ((!StringUtils.isEmpty(sFlag)) && ("1".equals(sFlag))) {
			customerName = request.getParameter("customerName");
		}
		map.put("customerName", customerName);

		QueryContract qContract = null;
		if ((!StringUtils.isEmpty(sFlag)) && ("2".equals(sFlag))) {
			qContract = queryContract;
		}
		map.put("queryContract", qContract);

		Page page = new Page();
		page.getPageList(
				this.contractService.getPageMyContractsCount(isViewAllContract,
						"2", customerName, userId, qContract).intValue(), null,
				request);
		map.put("contracts", this.contractService.getPageMyContracts(
				isViewAllContract, "2", customerName, userId, page, qContract));

		return new ModelAndView(getContractManage(), map);
	}

	public ModelAndView reverseInvoiceDetail(HttpServletRequest request,
			HttpServletResponse response) {
		String invoiceId = request.getParameter("invoiceId");
		Invoice invoice = new Invoice();
		Map model = new HashMap();
		if (invoiceId != null && !("").equals(invoiceId)) {
			invoice = contractInvoiceService.getInvoiceById(Integer
					.parseInt(invoiceId));
			model.put("invoice", invoice);
			List<ContractCase> ccList = contractService
					.getContractCasesByContractCode(invoice.getContractId()
							+ "");
			model.put("contractCases", ccList);
		}
		return new ModelAndView(getReverseInvoiceDetail(), model);
	}
	
	public ModelAndView addInvoiceNew(HttpServletRequest request,
			HttpServletResponse response, InvoiceNewForm invoiceNewForm) {
		boolean result = false;
		int success = 0;
		if (invoiceNewForm != null) {
			result = this.contractInvoiceService.insertInvoiceNew(invoiceNewForm);
		}
		if (result)
			success = 1;
		return new ModelAndView(new RedirectView(
				"./contract.do?action=preAddInvoice&id="
						+ invoiceNewForm.getContractId() + "&result=" + success));
	}

	public ModelAndView preAddReverseInvoice(HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("id");
		Map model = new HashMap();
		if (!StringUtils.isEmpty(id)) {
			model.put("contractId", id);
			model.put("invoiceList", this.contractInvoiceService
					.getInvoices(Integer.parseInt(id)));
		}
		return new ModelAndView(getAddReverseInvoice(), model);
	}

	public ModelAndView selectContract(HttpServletRequest request,
			HttpServletResponse response) {
		String contractId = request.getParameter("contractId");
		List<Contract> contractList = new ArrayList<Contract>();
		if (contractId != null && !("").equals(contractId))
			contractList = contractService
					.getContractListBySameCustomer(Integer.parseInt(contractId));
		Map map = new HashMap();
		map.put("contractList", contractList);
		return new ModelAndView(getSelectContractList(), map);

	}

	public ModelAndView advancedQueryContract(HttpServletRequest request,
			HttpServletResponse response) {
		Map map = new HashMap();
		Integer userId = (Integer) request.getSession().getAttribute("userId");
		List users = new ArrayList();
		if (userId != null) {
			String deptIds = this.departmentService
					.getCurrentDeptIdAndSubDeptIdsByUserId(userId);
			users = this.userService.getActivityUsersByDeptIds(deptIds);
		}
		map.put("users", users);
		return new ModelAndView(getAdvancedQueryContract(), map);
	}

	public ModelAndView selectCaseTypeDetail(HttpServletRequest request,
			HttpServletResponse response) {
		String typeId = request.getParameter("typeId");
		ContractCaseType caseType = contractCaseService.getCaseType(typeId);
		String a = "", b = "";
		// a,b
		if (caseType.getCodeRole() != null
				&& !"".equals(caseType.getCodeRole())) {
			String[] val = caseType.getCodeRole().split(",");
			a = val[0];
			b = val[1];
		}
		// 两位数年
		Calendar calendar = Calendar.getInstance();
		String year = String.valueOf(calendar.get(Calendar.YEAR)).substring(2,
				4);
		// 得到流水号
		Long seq = contractService.selectCaseSeq();
		java.text.DecimalFormat df = new java.text.DecimalFormat("0000 ");
		// String seq="0001";
		// 生成案号
		String caseCode = a + year + b + df.format(seq);
		Map map = new HashMap();
		map.put("caseCode", caseCode.trim());
		map.put("firstProcess", caseType.getProcessGroup().getProcessList()
				.get(0).getName());
		map.put("processId", caseType.getProcessGroup().getProcessList().get(0)
				.getId());
		map.put("processGroupId", caseType.getProcessGroup().getId());
		// map.put("caseType", caseType);
		return new ModelAndView(getAjaxCaseType(), map);
	}

	// Display CaseType Choose
	public ModelAndView selectCaseType(HttpServletRequest request,
			HttpServletResponse response) {
		List<ContractCaseType> caseList = customerService.getPageAllCaseTypes(
				"", null);
		Map map = new HashMap();
		map.put("caseTypes", caseList);
		return new ModelAndView(getSelectContractCaseType(), map);
	}

	// Display CaseType Choose
	public ModelAndView selectProcess(HttpServletRequest request,
			HttpServletResponse response) {
		Map map = new HashMap();
//		Integer userId = (Integer) request.getSession().getAttribute("userId");
//		String isViewAllContract = (String) request.getSession().getAttribute(
//				"isViewAllContract");

//		String sFlag = request.getParameter("sFlag");
		String processGroupId = request.getParameter("processGroupId");
//		String indexFlag = "";
//		if (!StringUtils.isEmpty(sFlag) && "1".equals(sFlag)) {
//			indexFlag = request.getParameter("indexFlag");
//		}
//		map.put("sFlag", sFlag);
//		map.put("processId", processGroupId);
//		map.put("indexFlag", indexFlag);

//		Page page = new Page();
//		page.getPageList(customerService.getPageAllProcessGroupCount(processGroupId), 10,request);
//		map.put("processGroups",customerService.getPageAllProcessGroup(processGroupId, page));
        List<com.feeyin.radar.crm.model.Process> processList = contractCaseService.getProcessListByGroupId(Long.valueOf(processGroupId));
        map.put("processList", processList);
		return new ModelAndView(getSelectProcess(), map);
	}

	public ModelAndView selectCustomer(HttpServletRequest request,
			HttpServletResponse response) {
		Map map = new HashMap();
		Integer userId = (Integer) request.getSession().getAttribute("userId");
		String isViewAllContract = (String) request.getSession().getAttribute(
				"isViewAllContract");

		String sFlag = request.getParameter("sFlag");
		String customerName = "";
		if ((!StringUtils.isEmpty(sFlag)) && ("1".equals(sFlag))) {
			customerName = request.getParameter("customerName");
		}
		map.put("sFlag", sFlag);
		map.put("customerName", customerName);

		Page page = new Page();
		if ((!StringUtils.isEmpty(isViewAllContract))
				&& ("1".equals(isViewAllContract))) {
			page.getPageList(
					this.customerService.getPageAllCustomerCount(customerName)
							.intValue(), Integer.valueOf(10), request);
			map.put("customers", this.customerService.getPageAllCustomers(
					customerName, page));
		} else {
			page.getPageList(
					this.customerService
							.getPageMyAllCustomersCountByCustomerName(
									customerName, userId).intValue(), Integer
							.valueOf(10), request);
			map.put("customers", this.customerService
					.getPageMyAllCustomersByCustomerName(customerName, userId,
							page));
		}
		return new ModelAndView(getSelectCustomer(), map);
	}

	public ModelAndView selectMyAllCustomer(HttpServletRequest request,
			HttpServletResponse response) {
		Map map = new HashMap();
		Integer userId = (Integer) request.getSession().getAttribute("userId");

		String sFlag = request.getParameter("sFlag");
		String customerName = "";
		if ((!StringUtils.isEmpty(sFlag)) && ("1".equals(sFlag))) {
			customerName = request.getParameter("customerName");
		}
		map.put("sFlag", sFlag);
		map.put("customerName", customerName);

		Page page = new Page();
		page.getPageList(this.customerService
				.getPageMyAllCustomersCountByCustomerName(customerName, userId)
				.intValue(), Integer.valueOf(10), request);
		map.put("customers",
				this.customerService.getPageMyAllCustomersByCustomerName(
						customerName, userId, page));
		return new ModelAndView(getSelectCustomer(), map);
	}

	public ModelAndView selectSalePerson(HttpServletRequest request,
			HttpServletResponse response) {
		Map model = new HashMap();

		model.put("users", this.userService.getActivityUsers());
		return new ModelAndView(getSelectSalePerson(), model);
	}

	public ModelAndView preAddContract(HttpServletRequest request,
			HttpServletResponse response, ContractForm contractForm) {
		Map map = new HashMap();
		Integer userId = (Integer) request.getSession().getAttribute("userId");
		Users user = userService.getUser(userId);

		CodeStore codeStore = this.contractService
				.getCodeStoreByType("contract");
		request.setAttribute("user", user);
		request.setAttribute("codeStore", codeStore);

		map.put("result", request.getParameter("result"));
		map.put("failResult", request.getAttribute("failResult"));
		map.put("repeatResult", request.getAttribute("repeatResult"));
		if (contractForm != null
				&& (contractForm.getContractCaseStr() != null && !("")
						.equals(contractForm.getContractCaseStr()))) {
			List<ContractCase> ccList = this.contractService
					.getContractCaseListByCaseCode(contractForm
							.getContractCaseStr());
			StringBuffer sb = new StringBuffer();
			for (ContractCase cc : ccList) {
				sb.append(cc.getCaseCode() + "==");
			}
			// contractForm.setCaseCode(sb.substring(0, sb.length()-2));
			map.put("contractCaseList", ccList);
		}

		return new ModelAndView(getAddContract(), map);
	}

	public ModelAndView preAddContractN(HttpServletRequest request,
			HttpServletResponse response) {
		Map map = new HashMap();
		map.put("result", request.getParameter("result"));
		map.put("failResult", request.getAttribute("failResult"));
		map.put("repeatResult", request.getAttribute("repeatResult"));

		return new ModelAndView(getAddContractN(), map);
	}

	public ModelAndView preAddContractCase(HttpServletRequest request,
			HttpServletResponse response) {
		Map map = new HashMap();
		map.put("result", request.getParameter("result"));
		map.put("failResult", request.getAttribute("failResult"));
		map.put("repeatResult", request.getAttribute("repeatResult"));
		map.put("mark", request.getParameter("mark"));
		map.put("isSub", request.getParameter("isSub"));
		map.put("processGroupId",  request.getParameter("processGroupId"));
		map.put("processId",  request.getParameter("processId"));
		map.put("processName",  request.getParameter("processName"));
		map.put("applicationCode",  request.getParameter("applicationCode"));
		map.put("description",  request.getParameter("description"));
		map.put("applicationDate",  request.getParameter("applicationDate"));
		return new ModelAndView(getPreAddContractCase(), map);
	}

	public ModelAndView addContract(HttpServletRequest request,
			HttpServletResponse response, ContractForm contractForm) {
		MultipartFile multipartFile = contractForm.getContents();
		if ((multipartFile != null) && (!multipartFile.isEmpty())
				&& (multipartFile.getSize() > 10000000L)) {
			request.setAttribute("failResult", Integer.valueOf(3));
			request.setAttribute("contract", contractForm);
			request.setAttribute("contractDetails",
					getContractDetails(contractForm));
			return preAddContractN(request, response);
		}

		if ((contractForm != null)
				&& (this.contractService.isRepeatAddContract(contractForm
						.getContractCode()))) {
			request.setAttribute("repeatResult", Integer.valueOf(1));
			request.setAttribute("contract", contractForm);
			request.setAttribute("contractDetails",
					getContractDetails(contractForm));
			return preAddContractN(request, response);
		}

		String realPath = "";
		if ((multipartFile != null) && (!multipartFile.isEmpty())) {
			realPath = getServletContext().getRealPath("/");
		}

		boolean result = false;
		int success = 0;
		result = this.contractService.insertContract(contractForm, realPath,
				multipartFile);
		if (result)
			success = 1;
		return new ModelAndView(new RedirectView(
				"./contract.do?action=preAddContract&result=" + success));
	}

	public ModelAndView deleteContractCase(HttpServletRequest request,
			HttpServletResponse response, ContractForm contractForm) {
		String delContractCaseStr = contractForm.getDelContractCaseStr();

		boolean result = false;
		int success = 0;
		result = this.contractService.deleteContractCase(delContractCaseStr);
		if (result)
			success = 1;
		return new ModelAndView(new RedirectView(
				"./contract.do?action=preAddContract&result=" + success));
	}

	public ModelAndView preUpdateContract(HttpServletRequest request,
			HttpServletResponse response) {
		Map model = new HashMap();
		model.put("sign", request.getParameter("sign"));
		model.put("result", request.getParameter("result"));
		model.put("deleteResult", request.getParameter("deleteResult"));
		Integer failResult = (Integer) request.getAttribute("failResult");
		model.put("failResult", failResult);
		Integer repeatResult = (Integer) request.getAttribute("repeatResult");
		model.put("repeatResult", repeatResult);
		Integer uploadResult = (Integer) request.getAttribute("uploadResult");
		model.put("uploadResult", uploadResult);

		String realPath = realPath = getServletContext().getRealPath("/");
		String id = request.getParameter("id");
		if ((!StringUtils.isEmpty(id))
				&& ((failResult == null) || (failResult.intValue() != 3))
				&& ((repeatResult == null) || (repeatResult.intValue() != 1))
				&& ((uploadResult == null) || (uploadResult.intValue() != 4))) {
			model.put("contract", this.contractService.getContractById(Integer
					.valueOf(Integer.parseInt(id))));
			model.put("contractAddeds", this.contractService
					.getContractAddedsById(realPath,
							Integer.valueOf(Integer.parseInt(id))));
			model.put("contractDetails", this.contractService
					.getContractDetailsByContractId(Integer.valueOf(Integer
							.parseInt(id))));
			 List<ContractDetail> casesList = contractCaseService.convertContractCaseInfoIntoVO(Long.valueOf(id));
		      model.put("caseList",casesList);
		}
		return new ModelAndView(getUpdateContract(), model);
	}

	public ModelAndView addContractCase(HttpServletRequest request,
			HttpServletResponse response, ContractCaseForm contractCaseForm) {
		MultipartFile multipartFile = null;
		if ((multipartFile != null) && (!multipartFile.isEmpty())
				&& (multipartFile.getSize() > 10000000L)) {
			request.setAttribute("failResult", Integer.valueOf(3));
			request.setAttribute("contract", contractCaseForm);
			return preAddContractN(request, response);
		}

		if ((contractCaseForm != null)
				&& (this.contractService.isRepeatAddContract(contractCaseForm
						.getContractCode()))) {
			request.setAttribute("repeatResult", Integer.valueOf(1));
			request.setAttribute("contract", contractCaseForm);
			return preAddContractN(request, response);
		}

		String realPath = "";
		if ((multipartFile != null) && (!multipartFile.isEmpty())) {
			realPath = getServletContext().getRealPath("/");
		}

		boolean result = false;
		int success = 0;
		if (contractCaseForm.getCaseCode() != null
				&& !("").equals(contractCaseForm.getCaseCode()))
			result = this.contractService.insertContractCase(contractCaseForm,
					realPath, multipartFile);

		if (result)
			success = 1;
		return new ModelAndView(getPreAddContractCase());
	}

	public ModelAndView preUpdateContractProName(HttpServletRequest request,
			HttpServletResponse response) {
		Map model = new HashMap();
		model.put("sign", request.getParameter("sign"));
		model.put("result", request.getParameter("result"));
		model.put("deleteResult", request.getParameter("deleteResult"));
		Integer failResult = (Integer) request.getAttribute("failResult");
		model.put("failResult", failResult);
		Integer repeatResult = (Integer) request.getAttribute("repeatResult");
		model.put("repeatResult", repeatResult);
		Integer uploadResult = (Integer) request.getAttribute("uploadResult");
		model.put("uploadResult", uploadResult);

		String realPath = realPath = getServletContext().getRealPath("/");
		String id = request.getParameter("id");
		if ((!StringUtils.isEmpty(id))
				&& ((failResult == null) || (failResult.intValue() != 3))
				&& ((repeatResult == null) || (repeatResult.intValue() != 1))
				&& ((uploadResult == null) || (uploadResult.intValue() != 4))) {
			model.put("contract", this.contractService.getContractById(Integer
					.valueOf(Integer.parseInt(id))));
			model.put("contractAddeds", this.contractService
					.getContractAddedsById(realPath,
							Integer.valueOf(Integer.parseInt(id))));
			model.put("contractDetails", this.contractService
					.getContractDetailsByContractId(Integer.valueOf(Integer
							.parseInt(id))));
		}
		return new ModelAndView(getUpdateContractProName(), model);
	}

	public ModelAndView updateContract(HttpServletRequest request,
			HttpServletResponse response, ContractForm contractForm) {
		String sign = request.getParameter("sign");
		request.setAttribute("sign", sign);
		Integer userId = (Integer) request.getSession().getAttribute("userId");
		String realPath = realPath = getServletContext().getRealPath("/");

		MultipartFile multipartFile = contractForm.getContents();
		if ((multipartFile != null) && (!multipartFile.isEmpty())
				&& (multipartFile.getSize() > 10000000L)) {
			request.setAttribute("failResult", Integer.valueOf(3));
			request.setAttribute("contract", contractForm);
			if ((contractForm != null) && (contractForm.getId() != null)) {
				request.setAttribute("contractAddeds", this.contractService
						.getContractAddedsById(realPath, contractForm.getId()));
			}
			request.setAttribute("contractDetails",
					getContractDetails(contractForm));
			return preUpdateContract(request, response);
		}

		if ((contractForm != null)
				&& (this.contractService.isRepeatUpdateContract(
						contractForm.getId(), contractForm.getContractCode()))) {
			request.setAttribute("repeatResult", Integer.valueOf(1));
			request.setAttribute("contract", contractForm);
			if ((contractForm != null) && (contractForm.getId() != null)) {
				request.setAttribute("contractAddeds", this.contractService
						.getContractAddedsById(realPath, contractForm.getId()));
			}
			request.setAttribute("contractDetails",
					getContractDetails(contractForm));
			return preUpdateContract(request, response);
		}

		if ((multipartFile != null) && (!multipartFile.isEmpty())
				&& (contractForm != null)) {
			boolean isFileExists = false;
			isFileExists = this.contractService.isFileExists(realPath, null,
					contractForm.getCustomerId(), contractForm.getId(),
					multipartFile.getOriginalFilename());
			if (isFileExists) {
				request.setAttribute("uploadResult", Integer.valueOf(4));
				request.setAttribute("contract", contractForm);
				if ((contractForm != null) && (contractForm.getId() != null)) {
					request.setAttribute("contractAddeds", this.contractService
							.getContractAddedsById(realPath,
									contractForm.getId()));
				}
				request.setAttribute("contractDetails",
						getContractDetails(contractForm));
				return preUpdateContract(request, response);
			}
		}

		boolean result = false;
		int success = 0;
		result = this.contractService.updateContract(contractForm, realPath,
				multipartFile, userId);
		if (result)
			success = 1;
		return new ModelAndView(new RedirectView(
				"./contract.do?action=preUpdateContract&result=" + success
						+ "&id=" + contractForm.getId() + "&sign=" + sign));
	}

	public ModelAndView updateContractProName(HttpServletRequest request,
			HttpServletResponse response, ContractForm contractForm) {
		String sign = request.getParameter("sign");
		request.setAttribute("sign", sign);
		Integer userId = (Integer) request.getSession().getAttribute("userId");
		String realPath = realPath = getServletContext().getRealPath("/");

		MultipartFile multipartFile = contractForm.getContents();
		if ((multipartFile != null) && (!multipartFile.isEmpty())
				&& (multipartFile.getSize() > 10000000L)) {
			request.setAttribute("failResult", Integer.valueOf(3));
			request.setAttribute("contract", contractForm);
			if ((contractForm != null) && (contractForm.getId() != null)) {
				request.setAttribute("contractAddeds", this.contractService
						.getContractAddedsById(realPath, contractForm.getId()));
			}
			request.setAttribute("contractDetails",
					getContractDetails(contractForm));
			return preUpdateContract(request, response);
		}

		if ((contractForm != null)
				&& (this.contractService.isRepeatUpdateContract(
						contractForm.getId(), contractForm.getContractCode()))) {
			request.setAttribute("repeatResult", Integer.valueOf(1));
			request.setAttribute("contract", contractForm);
			if ((contractForm != null) && (contractForm.getId() != null)) {
				request.setAttribute("contractAddeds", this.contractService
						.getContractAddedsById(realPath, contractForm.getId()));
			}
			request.setAttribute("contractDetails",
					getContractDetails(contractForm));
			return preUpdateContract(request, response);
		}

		if ((multipartFile != null) && (!multipartFile.isEmpty())
				&& (contractForm != null)) {
			boolean isFileExists = false;
			isFileExists = this.contractService.isFileExists(realPath, null,
					contractForm.getCustomerId(), contractForm.getId(),
					multipartFile.getOriginalFilename());
			if (isFileExists) {
				request.setAttribute("uploadResult", Integer.valueOf(4));
				request.setAttribute("contract", contractForm);
				if ((contractForm != null) && (contractForm.getId() != null)) {
					request.setAttribute("contractAddeds", this.contractService
							.getContractAddedsById(realPath,
									contractForm.getId()));
				}
				request.setAttribute("contractDetails",
						getContractDetails(contractForm));
				return preUpdateContract(request, response);
			}
		}

		boolean result = false;
		int success = 0;
		result = this.contractService.updateContract(contractForm, realPath,
				multipartFile, userId);
		if (result)
			success = 1;
		return new ModelAndView(new RedirectView(
				"./contract.do?action=preUpdateContractProName&result="
						+ success + "&id=" + contractForm.getId() + "&sign="
						+ sign));
	}

	public ModelAndView deleteAdded(HttpServletRequest request,
			HttpServletResponse response) {
		String realPath = realPath = getServletContext().getRealPath("/");
		String sign = request.getParameter("sign");
		String customerId = request.getParameter("customerId");
		String contractId = request.getParameter("id");
		String addedId = request.getParameter("addedId");
		boolean result = false;
		int success = 0;
		if (!StringUtils.isEmpty(addedId)) {
			result = this.contractService.deleteAdded(realPath,
					Integer.valueOf(Integer.parseInt(addedId)));
			if (result)
				success = 1;
		}
		return new ModelAndView(new RedirectView(
				"./contract.do?action=preUpdateContract&id=" + contractId
						+ "&deleteResult=" + success + "&sign=" + sign));
	}

	public ModelAndView preStopContract(HttpServletRequest request,
			HttpServletResponse response) {
		Map model = new HashMap();
		model.put("sign", request.getParameter("sign"));
		model.put("result", request.getParameter("result"));
		model.put("deleteResult", request.getParameter("deleteResult"));
		Integer uploadResult = (Integer) request.getAttribute("uploadResult");
		model.put("uploadResult", uploadResult);

		String realPath = realPath = getServletContext().getRealPath("/");
		String id = request.getParameter("id");
		if ((!StringUtils.isEmpty(id))
				&& ((uploadResult == null) || (uploadResult.intValue() != 3) || (uploadResult
						.intValue() != 4))) {
			model.put("contract", this.contractService.getContractById(Integer
					.valueOf(Integer.parseInt(id))));
			model.put("contractAddeds", this.contractService
					.getContractAddedsById(realPath,
							Integer.valueOf(Integer.parseInt(id))));
			model.put("contractDetails", this.contractService
					.getContractDetailsByContractId(Integer.valueOf(Integer
							.parseInt(id))));
		}
		return new ModelAndView(getStopContract(), model);
	}

	public ModelAndView stopContract(HttpServletRequest request,
			HttpServletResponse response, ContractForm contractForm) {
		String realPath = realPath = getServletContext().getRealPath("/");
		MultipartFile multipartFile = contractForm.getContents();
		if ((multipartFile != null) && (!multipartFile.isEmpty())
				&& (multipartFile.getSize() > 10000000L)) {
			request.setAttribute("uploadResult", Integer.valueOf(3));
			request.setAttribute("contract", contractForm);
			if ((contractForm != null) && (contractForm.getId() != null)) {
				request.setAttribute("contractAddeds", this.contractService
						.getContractAddedsById(realPath, contractForm.getId()));
			}
			request.setAttribute("contractDetails",
					getContractDetails(contractForm));
			return preStopContract(request, response);
		}

		if ((multipartFile != null) && (!multipartFile.isEmpty())
				&& (contractForm != null)) {
			boolean isFileExists = false;
			isFileExists = this.contractService.isFileExists(realPath, null,
					contractForm.getCustomerId(), contractForm.getId(),
					multipartFile.getOriginalFilename());
			if (isFileExists) {
				request.setAttribute("uploadResult", Integer.valueOf(4));
				request.setAttribute("contract", contractForm);
				if ((contractForm != null) && (contractForm.getId() != null)) {
					request.setAttribute("contractAddeds", this.contractService
							.getContractAddedsById(realPath,
									contractForm.getId()));
				}
				request.setAttribute("contractDetails",
						getContractDetails(contractForm));
				return preStopContract(request, response);
			}
		}

		String sign = request.getParameter("sign");
		boolean result = false;
		int success = 0;
		result = this.contractService.stopContract(contractForm, realPath,
				multipartFile);
		if (result)
			success = 1;
		return new ModelAndView(new RedirectView(
				"./contract.do?action=preStopContract&result=" + success
						+ "&id=" + contractForm.getId() + "&sign=" + sign));
	}

	public ModelAndView deleteStopContractAdded(HttpServletRequest request,
			HttpServletResponse response) {
		String realPath = realPath = getServletContext().getRealPath("/");
		String contractId = request.getParameter("id");
		String addedId = request.getParameter("addedId");
		boolean result = false;
		int success = 0;
		if (!StringUtils.isEmpty(addedId)) {
			result = this.contractService.deleteAdded(realPath,
					Integer.valueOf(Integer.parseInt(addedId)));
			if (result)
				success = 1;
		}
		return new ModelAndView(new RedirectView(
				"./contract.do?action=preStopContract&id=" + contractId
						+ "&deleteResult=" + success));
	}

	public ModelAndView preWaitAduitContract(HttpServletRequest request,
			HttpServletResponse response) {
		Map model = new HashMap();
		model.put("result", request.getParameter("result"));
		Integer userId = (Integer) request.getSession().getAttribute("userId");

		Page page = new Page();
		page.getPageList(
				this.contractService.getPageMyContractsCount(null, "1", null,
						userId, null).intValue(), null, request);
		model.put("waitAduitContracts", this.contractService
				.getPageMyContracts(null, "1", null, userId, page, null));
		return new ModelAndView(getWaitAuditContract(), model);
	}

	public ModelAndView preCancelContractByWaitAudit(
			HttpServletRequest request, HttpServletResponse response) {
		Map model = new HashMap();
		String sign = request.getParameter("sign");
		model.put("sign", sign);
		String action = "preWaitAduitContract";
		if ((!StringUtils.isEmpty(sign)) && ("2".equals(sign))) {
			action = "preReturnContract";
		}
		String realPath = realPath = getServletContext().getRealPath("/");
		String id = request.getParameter("id");
		if (!StringUtils.isEmpty(id)) {
			if (!this.contractService.isExistContractTemp(Integer
					.valueOf(Integer.parseInt(id)))) {
				boolean result = false;
				int success = 0;
				result = this.contractService.deleteContractAndDetail(Integer
						.valueOf(Integer.parseInt(id)));
				if (result)
					success = 1;
				return new ModelAndView(
						new RedirectView("./contract.do?action=" + action
								+ "&result=" + success));
			}

			model.put("deleteResult", request.getParameter("deleteResult"));
			Integer uploadResult = (Integer) request
					.getAttribute("uploadResult");
			model.put("uploadResult", uploadResult);
			if ((!StringUtils.isEmpty(id))
					&& ((uploadResult == null)
							|| (uploadResult.intValue() != 3) || (uploadResult
							.intValue() != 4))) {
				model.put("contract", this.contractService
						.getContractById(Integer.valueOf(Integer.parseInt(id))));
				model.put("contractAddeds", this.contractService
						.getContractAddedsById(realPath,
								Integer.valueOf(Integer.parseInt(id))));
				model.put("contractDetails", this.contractService
						.getContractDetailsByContractId(Integer.valueOf(Integer
								.parseInt(id))));
			}
		}
		return new ModelAndView(getCancelContract(), model);
	}

	public ModelAndView cancelContractByWaitAudit(HttpServletRequest request,
			HttpServletResponse response, ContractForm contractForm) {
		String sign = request.getParameter("sign");
		String action = "preWaitAduitContract";
		if ((!StringUtils.isEmpty(sign)) && ("2".equals(sign))) {
			action = "preReturnContract";
		}

		String realPath = realPath = getServletContext().getRealPath("/");
		MultipartFile multipartFile = contractForm.getContents();
		if ((multipartFile != null) && (!multipartFile.isEmpty())
				&& (multipartFile.getSize() > 10000000L)) {
			request.setAttribute("uploadResult", Integer.valueOf(3));
			request.setAttribute("contract", contractForm);
			if ((contractForm != null) && (contractForm.getId() != null)) {
				request.setAttribute("contractAddeds", this.contractService
						.getContractAddedsById(realPath, contractForm.getId()));
			}
			request.setAttribute("contractDetails",
					getContractDetails(contractForm));
			request.setAttribute("sign", sign);
			return preCancelContractByWaitAudit(request, response);
		}

		if ((multipartFile != null) && (!multipartFile.isEmpty())
				&& (contractForm != null)) {
			boolean isFileExists = false;
			isFileExists = this.contractService.isFileExists(realPath, null,
					contractForm.getCustomerId(), contractForm.getId(),
					multipartFile.getOriginalFilename());
			if (isFileExists) {
				request.setAttribute("uploadResult", Integer.valueOf(4));
				request.setAttribute("contract", contractForm);
				if ((contractForm != null) && (contractForm.getId() != null)) {
					request.setAttribute("contractAddeds", this.contractService
							.getContractAddedsById(realPath,
									contractForm.getId()));
				}
				request.setAttribute("contractDetails",
						getContractDetails(contractForm));
				request.setAttribute("sign", sign);
				return preCancelContractByWaitAudit(request, response);
			}
		}

		boolean result = false;
		int success = 0;
		result = this.contractService.cancelContract(contractForm, realPath,
				multipartFile);
		if (result)
			success = 1;
		return new ModelAndView(new RedirectView("./contract.do?action="
				+ action + "&result=" + success));
	}

	public ModelAndView deleteCancelContractAdded(HttpServletRequest request,
			HttpServletResponse response) {
		String realPath = realPath = getServletContext().getRealPath("/");
		String sign = request.getParameter("sign");
		String contractId = request.getParameter("id");
		String addedId = request.getParameter("addedId");
		boolean result = false;
		int success = 0;
		if (!StringUtils.isEmpty(addedId)) {
			result = this.contractService.deleteAdded(realPath,
					Integer.valueOf(Integer.parseInt(addedId)));
			if (result)
				success = 1;
		}
		return new ModelAndView(new RedirectView(
				"./contract.do?action=preCancelContractByWaitAudit&id="
						+ contractId + "&deleteResult=" + success + "&sign="
						+ sign));
	}

	public ModelAndView preReturnContract(HttpServletRequest request,
			HttpServletResponse response) {
		Map model = new HashMap();
		model.put("result", request.getParameter("result"));
		Integer userId = (Integer) request.getSession().getAttribute("userId");

		Page page = new Page();
		page.getPageList(
				this.contractService.getPageMyContractsCount(null, "3", null,
						userId, null).intValue(), null, request);
		model.put("returnContracts", this.contractService.getPageMyContracts(
				null, "3", null, userId, page, null));
		return new ModelAndView(getReturnContract(), model);
	}

	public ModelAndView preClosedContract(HttpServletRequest request,
			HttpServletResponse response, QueryContract queryContract) {
		Map model = new HashMap();
		model.put("result", request.getParameter("result"));
		Integer userId = (Integer) request.getSession().getAttribute("userId");
		String isViewAllContract = (String) request.getSession().getAttribute(
				"isViewAllContract");
		String sFlag = request.getParameter("sFlag");
		model.put("sFlag", sFlag);
		QueryContract qContract = null;
		if ((!StringUtils.isEmpty(sFlag)) && ("2".equals(sFlag))) {
			qContract = queryContract;
		}
		Page page = new Page();
		model.put("queryContract", qContract);
		page.getPageList(
				this.contractService.getPageMyContractsCount(isViewAllContract,
						"4", null, userId, qContract).intValue(), null, request);
		model.put("closedContracts", this.contractService.getPageMyContracts(
				isViewAllContract, "4", null, userId, page, qContract));
		return new ModelAndView(getClosedContract(), model);
	}

	public ModelAndView preDeptContract(HttpServletRequest request,
			HttpServletResponse response, QueryContract queryContract) {
		Map model = new HashMap();
		model.put("result", request.getParameter("result"));
		Integer userId = (Integer) request.getSession().getAttribute("userId");
		String sFlag = request.getParameter("sFlag");
		String customerName = "";
		if ((!StringUtils.isEmpty(sFlag)) && ("1".equals(sFlag))) {
			customerName = request.getParameter("customerName");
		}
		model.put("sFlag", sFlag);
		model.put("customerName", customerName);

		QueryContract qContract = null;
		if ((!StringUtils.isEmpty(sFlag)) && ("2".equals(sFlag))) {
			qContract = queryContract;
		}
		model.put("queryContract", qContract);
		Page page = new Page();
		page.getPageList(
				this.contractService.getPageDetpContractsCount(customerName,
						userId, qContract).intValue(), null, request);
		model.put("deptContracts", this.contractService.getPageDeptContracts(
				customerName, userId, page, qContract));
		return new ModelAndView(getDeptContract(), model);
	}

	public ModelAndView preImportContract(HttpServletRequest request,
			HttpServletResponse response) {
		return new ModelAndView(getImportContract());
	}

	public ModelAndView importContract(HttpServletRequest request,
			HttpServletResponse response, UploadFileForm uploadFileForm) {
		Map model = new HashMap();
		MultipartFile multipartFile = uploadFileForm.getContents();
		if (multipartFile == null) {
			request.setAttribute("result", Integer.valueOf(2));
			request.setAttribute("uploadFileForm", uploadFileForm);
			return preImportContract(request, response);
		}
		if (multipartFile.getSize() > 10000000L) {
			request.setAttribute("result", Integer.valueOf(3));
			request.setAttribute("uploadFileForm", uploadFileForm);
			return preImportContract(request, response);
		}

		Integer userId = (Integer) request.getSession().getAttribute("userId");
		List logs = new ArrayList();
		String realPath = getServletContext().getRealPath("/");
		logs = this.contractService.importContract(userId, uploadFileForm,
				realPath, multipartFile);
		model.put("logs", logs);

		return new ModelAndView(getImportContract(), model);
	}

	public ModelAndView downloadTemplate(HttpServletRequest request,
			HttpServletResponse response) {
		FileUtils fileUtils = new FileUtils();
		fileUtils.downloadCustomerTemplate(
				getServletContext().getRealPath("/"), response, 3);
		return null;
	}

	public ModelAndView contractDetail(HttpServletRequest request,
			HttpServletResponse response) {
		Map model = new HashMap();
		model.put("sign", request.getParameter("sign"));
		String realPath = realPath = getServletContext().getRealPath("/");
		String id = request.getParameter("id");
		if (!StringUtils.isEmpty(id)) {
			model.put("contract", this.contractService.getContractById(Integer
					.valueOf(Integer.parseInt(id))));
			model.put("contractAddeds", this.contractService
					.getContractAddedsById(realPath,
							Integer.valueOf(Integer.parseInt(id))));
			model.put("contractDetails", this.contractService
					.getContractDetailsByContractId(Integer.valueOf(Integer
							.parseInt(id))));
			model.put("contractCases", this.contractService.getContractCasesByContractCode(id));
			model.put("ranges",
					this.contractBackCostService.getBackCostDictionaryRanges());
			model.put("backCosts", this.contractBackCostService
					.getBackCosts(Integer.valueOf(Integer.parseInt(id))));
			model.put("invoices", this.contractInvoiceService
					.getInvoices(Integer.valueOf(Integer.parseInt(id))));
		}
		return new ModelAndView(getContractDetail(), model);
	}

	public ModelAndView downloadAdded(HttpServletRequest request,
			HttpServletResponse response) {
		String customerId = request.getParameter("customerId");
		String contractId = request.getParameter("id");
		String addedId = request.getParameter("addedId");

		String realPath = realPath = getServletContext().getRealPath("/");
		if ((!StringUtils.isEmpty(contractId))
				&& (!StringUtils.isEmpty(customerId))
				&& (!StringUtils.isEmpty(addedId))
				&& (!StringUtils.isEmpty(realPath))) {
			SystemFile systemFile = new SystemFile();
			systemFile = this.systemFileService.getSystemFile(Integer
					.valueOf(Integer.parseInt(addedId)));
			if (systemFile != null) {
				boolean isFileExists = false;
				isFileExists = this.contractService.isFileExists(null, realPath
						+ systemFile.getPath(),
						Integer.valueOf(Integer.parseInt(customerId)),
						Integer.valueOf(Integer.parseInt(contractId)),
						systemFile.getFileName());
				if (isFileExists) {
					String path = realPath + systemFile.getPath()
							+ systemFile.getFileName();
					try {
						File file = new File(path);

						String filename = file.getName();

						String ext = filename.substring(
								filename.lastIndexOf(".") + 1).toUpperCase();

						InputStream fis = new BufferedInputStream(
								new FileInputStream(path));
						byte[] buffer = new byte[fis.available()];
						fis.read(buffer);
						fis.close();

						response.reset();

						response.addHeader(
								"Content-Disposition",
								"attachment;filename="
										+ new String(filename.getBytes()));
						response.addHeader("Content-Length", file.length() + "");
						OutputStream toClient = new BufferedOutputStream(
								response.getOutputStream());
						response.setContentType("application/octet-stream");
						toClient.write(buffer);
						toClient.flush();
						toClient.close();
					} catch (IOException ex) {
						ex.printStackTrace();
					}
				}
			}
		}
		return null;
	}

	public ModelAndView contractUpdateHistory(HttpServletRequest request,
			HttpServletResponse response) {
		Map model = new HashMap();
		model.put("sign", request.getParameter("sign"));
		String id = request.getParameter("id");
		model.put("id", id);
		if (!StringUtils.isEmpty(id)) {
			model.put("contractDetailUpdateHistorys", this.contractService
					.getContractDetailUpdateHistorysByContractId(Integer
							.valueOf(Integer.parseInt(id))));
		}
		return new ModelAndView(getContractUpdateHistory(), model);
	}

	public ModelAndView preAddInvoice(HttpServletRequest request,
			HttpServletResponse response) {
		Map model = new HashMap();
		model.put("result", request.getParameter("result"));
		String id = request.getParameter("id");
		if (!StringUtils.isEmpty(id)) {
			model.put("contractId", id);
			model.put("contractCases", this.contractService.getContractCasesByContractCode(id));
		}
		return new ModelAndView(getAddInvoice(), model);
	}

	public ModelAndView addInvoice(HttpServletRequest request,
			HttpServletResponse response, InvoiceForm invoiceForm) {
		boolean result = false;
		int success = 0;
		if ((invoiceForm != null) && (invoiceForm.getContractId() != null)) {
			result = this.contractInvoiceService.insertInvoice(invoiceForm);
		}
		if (result)
			success = 1;
		return new ModelAndView(new RedirectView(
				"./contract.do?action=preAddInvoice&id="
						+ invoiceForm.getContractId() + "&result=" + success));
	}

	private List getContractDetails(ContractForm contractForm) {
		List contractDetails = new ArrayList();
		if (contractForm == null)
			return contractDetails;
		if ((contractForm.getPurchaseDesc() == null)
				|| (contractForm.getPurchaseDesc().length <= 0))
			return contractDetails;

		for (int i = 0; i < contractForm.getPurchaseDesc().length; i++) {
			if (!StringUtils.isEmpty(contractForm.getPurchaseDesc()[i])) {
				ContractDetail contractDetail = new ContractDetail();
				contractDetail
						.setPurchaseDesc(contractForm.getPurchaseDesc()[i]);
				if ((contractForm.getUnit() != null)
						&& (contractForm.getUnit().length > 0)) {
					contractDetail.setUnit(contractForm.getUnit()[i]);
				}
				if ((contractForm.getPrice() != null)
						&& (contractForm.getPrice().length > 0)) {
					contractDetail.setPrice(contractForm.getPrice()[i]);
				}
				if ((contractForm.getNum() != null)
						&& (contractForm.getNum().length > 0)) {
					contractDetail.setNum(contractForm.getNum()[i]);
				}
				if ((contractForm.getCostValue() != null)
						&& (contractForm.getCostValue().length > 0)) {
					contractDetail.setCostValue(contractForm.getCostValue()[i]);
				}
				if ((contractForm.getDiscount() != null)
						&& (contractForm.getDiscount().length > 0)) {
					contractDetail.setDiscount(contractForm.getDiscount()[i]);
				}
				if ((contractForm.getCosts() != null)
						&& (contractForm.getCosts().length > 0)) {
					contractDetail.setCosts(contractForm.getCosts()[i]);
				}
				if ((contractForm.getProssProfit() != null)
						&& (contractForm.getProssProfit().length > 0)) {
					contractDetail
							.setProssProfit(contractForm.getProssProfit()[i]);
				}
				contractDetails.add(contractDetail);
			}
		}
		return contractDetails;
	}

	public ModelAndView activationContract(HttpServletRequest request,
			HttpServletResponse response) {
		Integer id = Integer.valueOf(Integer.parseInt(request
				.getParameter("id")));
		Integer sign = Integer.valueOf(Integer.parseInt(request
				.getParameter("sign")));
		Contract contract = this.contractService.getContractById(id);
		Contract c = new Contract();
		c.setId(id);
		c.setReceivable(contract.getReceivable2());
		c.setStatus("2");
		this.contractService.updateContractByDynamic(c);
		QueryContract qc = new QueryContract();
		if (sign.intValue() == 1) {
			return preClosedContract(request, response, qc);
		}
		if (sign.intValue() == 2) {
			return preDeptContract(request, response, qc);
		}
		return null;
	}

	public ModelAndView deleteContract(HttpServletRequest request,
			HttpServletResponse response) {
		Integer id = Integer.valueOf(Integer.parseInt(request
				.getParameter("id")));
		Integer sign = Integer.valueOf(Integer.parseInt(request
				.getParameter("sign")));
		this.contractService.deleteContractAndDetail(id);
		QueryContract qc = new QueryContract();
		if (sign.intValue() == 1) {
			return preClosedContract(request, response, qc);
		}
		if (sign.intValue() == 2) {
			return preDeptContract(request, response, qc);
		}
		if (sign.intValue() == 3) {
			return display(request, response, qc);
		}
		return null;
	}

	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(Date.class, new DatePropertyEditor());
		binder.registerCustomEditor(BigDecimal.class,
				new BigDecimalPropertyEditor());
	}

	public void setContractCaseService(ContractCaseService contractCaseService) {
		this.contractCaseService = contractCaseService;
	}
	
	public ModelAndView preOfficialCostGen(HttpServletRequest request,
			HttpServletResponse response)
	{
		String caseIds = request.getParameter("caseIds");
		
		List<ContractCase> ccList = new ArrayList<ContractCase>();
		if(caseIds != null && !StringUtils.isEmpty(caseIds))
		{
			String[] caseIdAry = caseIds.split("/");
			ccList = contractService.getContractCaseListByIds(caseIdAry);
		}
			
		Map model = new HashMap();
		model.put("ccList", ccList);
		model.put("contractCaseIds", caseIds);
		return new ModelAndView(getAddOfficialCost(), model);
	}
	
	public ModelAndView preOperationCostGen(HttpServletRequest request,
			HttpServletResponse response)
	{
		String caseIds = request.getParameter("caseIds");
		
		List<ContractCase> ccList = new ArrayList<ContractCase>();
		if(caseIds != null && !StringUtils.isEmpty(caseIds))
		{
			String[] caseIdAry = caseIds.split("/");
			ccList = contractService.getContractCaseListByIds(caseIdAry);
		}
			
		Map model = new HashMap();
		model.put("ccList", ccList);
		model.put("contractCaseIds", caseIds);
		return new ModelAndView(getAddOperationCost(), model);
	}	
	
	public ModelAndView genOfficialCost(HttpServletRequest request,
			HttpServletResponse response, CostForm costForm)
	{
		Boolean result = contractService.insertCost(costForm);
		Integer success = 0;
		if(result)
			success = 1;
		
		return new ModelAndView(new RedirectView("./contract.do?action=display"));		
		
	}
	
	public ModelAndView genOperationCost(HttpServletRequest request,
			HttpServletResponse response, CostForm costForm)
	{
		Boolean result = contractService.insertCost(costForm);
		Integer success = 0;
		if(result)
			success = 1;
		
		return new ModelAndView(new RedirectView("./contract.do?action=display"));		
		
	}	
	
	public ModelAndView deptCost(HttpServletRequest request,
			HttpServletResponse response, CostForm costForm)
	{
		String costType = request.getParameter("costType");
		List<CostManage> costManageList = contractService.getCostManageListByType(costType);
		
		Map map = new HashMap();
		map.put("costList", costManageList);
		map.put("costType", costType);
		return new ModelAndView(getDeptCost(), map);
	}		
	
	public ModelAndView costDetail(HttpServletRequest request,
			HttpServletResponse response, CostForm costForm)
	{
		String costId = request.getParameter("costId");
		List<CostManage> costManageList = contractService.getCostManageListByCostId(costId);
		
		Map map = new HashMap();
		map.put("cost", costManageList.get(0));
		return new ModelAndView(getCostDetail(), map);
	}	
	
	
	public ModelAndView confirmCost(HttpServletRequest request,
			HttpServletResponse response, CostForm costForm)
	{
		Integer id = costForm.getId();		
		Integer successs = contractService.updateCostManage(id);
		
		return new ModelAndView(new RedirectView("./contract.do?action=deptCost&costType="+costForm.getCostType()));
	}
}